const base = require("./../../base");

module.exports = class extends base {
    async _initialize() {
        await super.isCustomAuth();
        await super.isAppAuth();
        await super.isShopAuth();
    }

    /**
     *
     * @api {get} /shop/home/shop/plugin/fee/index 运费列表
     * @apiDescription 运费列表
     * @apiGroup Shop/Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     *
     * @apiParam {Number} page 页码
     *
     * @apiSampleRequest /shop/home/shop/plugin/fee/index
     *
     */
    async index() {
        const shopId = this.state.shop.id;
        const { page = 1 } = this.query;
        const fee = await this.model("fee")
            .query(qb => {
                qb.where("shop_id", shopId);
                qb.orderBy("id", "desc");
            })
            .fetchPage({
                pageSize: 20,
                page: page
            });
        this.success(fee);
    }

    /**
     *
     * @api {get} /shop/home/shop/plugin/fee/add 新增/修改运费模板
     * @apiDescription 新增/修改运费模板
     * @apiGroup Shop/Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     *
     *
     * @apiSampleRequest /shop/home/shop/plugin/fee/add
     *
     */
    async add() {
        const shop_id = this.state.shop.id;
        const data = this.post;
        data.shop_id = shop_id;
        // 存入fee_sku_address表使用递归存入

        // 先存入fee表data
        const fee = data.fee;
        fee.shop_id = shop_id;
        if (fee.id === 0) {
            delete fee.id;
        }
        // 判断有无fee表中的id
        const fee_data = await this.model("fee")
            .forge(fee)
            .save();

        const deliveryfee_id = fee_data.id;
        // 操作fee_sku表
        const fee_sku = data.fee_sku;
        // 先更新fee_id

        for (let x = 0; x < fee_sku.length; x++) {
            fee_sku[x].deliveryfee_id = deliveryfee_id;
            if (fee_sku[x].id === 0) {
                delete fee_sku[x].id;
            }
        }

        // 存入fee_sku表,批量存入

        const fee_sku_data = await doodoo.bookshelf.Collection.extend({
            model: this.model("fee_sku")
        })
            .forge(fee_sku)
            .invokeThen("save");

        // 操作fee_sku_data表

        const fee_sku_address = data.fee_sku_address;

        for (let x = 0; x < fee_sku_address.length; x++) {
            const i = fee_sku_address[x].index;
            const data_row = fee_sku_address[i].data;
            // 获得fee_id和fee_sku表的id

            for (let y = 0; y < fee_sku_data.length; y++) {
                if (fee_sku_data[y].index === i) {
                    await this.addSkuAddress(
                        data_row,
                        deliveryfee_id,
                        fee_sku_data[y].id
                    );
                }
            }
        }

        this.success("保存成功");
    } // 选择模板地址

    /**
     *
     * @api {get} /shop/home/shop/plugin/fee/address 选择模板地址
     * @apiDescription 选择模板地址
     * @apiGroup Shop/Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     *
     *
     * @apiSampleRequest /shop/home/shop/plugin/fee/address
     *
     */
    async address() {
        // 全国地址
        const { id = 0, region_id = 0, type = 0, fee_sku_id = 0 } = this.query;
        // 刚进入选择全为省时;
        // 查询原表

        const regin_data = await this.model("region")
            .query(qb => {
                if (type === 0) {
                    qb.where("type", "=", type);
                }

                if (type > 0 && region_id !== 0) {
                    qb.where("pid", "=", region_id);
                }
            })
            .fetchAll();
        // 对所有上级给与默认全选
        for (let x = 0; x < regin_data.length; x++) {
            regin_data[x].ful = 1;
        }
        let select_address_data = "";
        // 查询已添加的表
        if (fee_sku_id || type === 0) {
            select_address_data = await this.model("fee_sku_address")
                .query(qb => {
                    if (type > 0) {
                        qb.where("deliveryfee_sku_id", "=", fee_sku_id);
                        qb.where("pid", "=", id);
                    }

                    if (type === 0) {
                        qb.where("pid", "=", 0);
                    }
                })
                .fetchAll();
        }
        const data = {
            regin_data: regin_data,
            select_address_data: select_address_data ? select_address_data : []
        };
        this.success(data);
    }

    /**
     *
     * @api {get} /shop/home/shop/plugin/fee/update 修改运费状态
     * @apiDescription 修改运费状态
     * @apiGroup Shop/Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     *
     * @apiParam {Number} id      运费id
     * @apiParam {Number} status  活动状态（1:开启，0：关闭）
     *
     * @apiSampleRequest /shop/home/shop/plugin/fee/update
     *
     */
    async update() {
        const { id, status } = this.query;
        const fee = await this.model("fee")
            .forge({
                id,
                status
            })
            .save();
        this.success(fee);
    }

    /**
     *
     * @api {get} /shop/home/shop/plugin/fee/index 删除运费
     * @apiDescription 删除运费
     * @apiGroup Shop/Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     *
     * @apiParam {Number} id      运费id
     *
     * @apiSampleRequest /shop/home/shop/plugin/fee/index
     *
     */
    async del() {
        const { id } = this.query;
        const shopId = this.state.shop.id;
        const fee = await this.model("fee")
            .query(qb => {
                qb.where("id", id);
            })
            .destroy();
        await this.model("fee_sku")
            .query(qb => {
                qb.where("shop_id", shopId);
                qb.where("deliveryfee_id", id);
            })
            .destroy();
        await this.model("fee_sku_address")
            .query(qb => {
                qb.where("shop_id", shopId);
                qb.where("deliveryfee_id", id);
            })
            .destroy();
        this.success(fee);
    }
};
